import 'dart:ffi';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:flutter_widgets_pc/theme/kq_theme_manager.dart';

import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import '../divider/kq_divider.dart';
import '../searchBar/kq_search_bar.dart';
import 'pull_down_menu_controller.dart';

// ignore: must_be_immutable
class PullDownMenuList extends StatefulWidget {
  /// 控制器
  PullDownMenuController controller;

  /// 是否是自定义组件，如果不是则会调用回调menuDataRender，否则会调用回调menuWidgetRender
  bool Function(int menuIndex) isShowCustomWidget;

  ///返回下拉菜单menuIndex对应的数据
  List<dynamic>? Function(int menuIndex)? menuDataRender;

  /// 非自定义需实现的方法
  /// 下拉菜单每一项绘制器，返回要显示的文本内容
  final String Function(dynamic item)? menuItemRender;

  ///返回下拉菜单menuIndex对应的widget
  Widget? Function(int menuIndex, PullDownMenuController menuController)?
      menuCustomWidgetRender;

  ///返回菜单header对应menuIndex下拉菜单对应的高度，默认最大308
  double Function(int menuIndex)? menuWidgetHeight;

  /// 选中菜单回调
  final Function(dynamic item, int menuIndex)? pullDownCallback;

  ///比较两个是否相同，相同选中
  final bool Function(dynamic item, dynamic compareItem)? isDataSame;

  ///是否显示排序数据，根据位置menuIndex来判断是否要显示排序号码
  final bool Function(int menuIndex)? isShowSortRender;

  ///返回搜索结果,两个参数：1.menu位置；2.搜索的内容
  final List<dynamic>? Function(int menuIndex, String searchContent)?
      searchResultCallback;

  ///动画时间
  final int animationMilliseconds;

  ///蒙版颜色
  final Color maskColor;

  ///是否使用Overlay
  final bool isUseOverlay;

  ///menu位置是否固定，默认是true
  final bool isFixure;

  PullDownMenuList({
    Key? key,
    required this.controller,
    required this.isShowCustomWidget,
    this.menuItemRender,
    this.menuCustomWidgetRender,
    this.menuDataRender,
    this.menuWidgetHeight,
    this.isDataSame,
    this.isShowSortRender,
    this.animationMilliseconds = 300,
    this.maskColor = const Color.fromRGBO(0, 0, 0, 0.3),
    this.pullDownCallback,
    this.searchResultCallback,
    this.isUseOverlay = false,
    this.isFixure = true,
  }) : super(key: key);

  @override
  State<PullDownMenuList> createState() => _PullDownMenuListState();
}

class _PullDownMenuListState extends State<PullDownMenuList>
    with SingleTickerProviderStateMixin {
  bool _isShowDropDownItemWidget = false;
  bool _isShowMask = false;
  bool _isControllerDisposed = false;
  Animation<double>? _animation;
  AnimationController? _controller;

  // late double _maskColorOpacity;

  double? _dropDownHeight;

  int _currentMenuIndex = 0;

  final Map<int, List<dynamic>> _aliveSearch = {};
  String? _aliveSearchContent;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onController);
    _controller = AnimationController(
        duration: Duration(milliseconds: widget.animationMilliseconds),
        vsync: this);
  }

  _onController() {
    // setState(() {});
    bool isReload = widget.controller.isReloadMenu;
    if (isReload) {
      // 为了让外部去刷新菜单
      setState(() {});
      widget.controller.isReloadMenu = false;
    } else {
      if (_isCustomWidget()) {
        renderDropDownCustomWidget();
      } else {
        renderDropDownWidget();
      }
    }
  }

  bool _isCustomWidget() {
    if (Get.isRegistered<PullDownMenuController>()) {
      return widget.isShowCustomWidget(widget.controller.menuIndex);
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    _controller!.duration =
        Duration(milliseconds: widget.animationMilliseconds);
    return _buildDropDownWidget();
  }

  @override
  dispose() {
    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    // Get.find<PullDownMenuController>().removeListener(_onController);
    _controller?.dispose();
    _isControllerDisposed = true;
    super.dispose();
  }

  //获取数据源
  List<dynamic>? getMenuData() {
    List<dynamic>? list = [];
    if (_aliveSearch[_currentMenuIndex] != null &&
        _aliveSearch[_currentMenuIndex]!.isNotEmpty) {
      list = _aliveSearch[_currentMenuIndex];
    } else {
      if (widget.menuDataRender != null) {
        list = widget.menuDataRender!(_currentMenuIndex);
      }
    }
    return list;
  }

  //默认样式Widget
  renderDropDownWidget() {
    if (!Get.isRegistered<PullDownMenuController>()) {
      return;
    }
    _currentMenuIndex = widget.controller.menuIndex;
    _isShowDropDownItemWidget = !_isShowDropDownItemWidget;

    if (!_isShowMask) {
      _isShowMask = true;
    }

    List<dynamic>? list = getMenuData();

    _dropDownHeight = 308;
    if (widget.menuWidgetHeight != null) {
      double menuH = widget.menuWidgetHeight!(_currentMenuIndex);
      if (menuH > 0) {
        _dropDownHeight = menuH;
      }
    } else if (list != null && list.isNotEmpty) {
      if (list.length * 44 < 308) {
        _dropDownHeight = list.length * 44;
      }
    }

    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    _animation = Tween(begin: 0.0, end: _dropDownHeight).animate(_controller!)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);
    if (_isControllerDisposed) return;

    if (widget.controller.isShow) {
      _controller!.forward();
    } else if (widget.controller.isShowHideAnimation) {
      _controller!.reverse();
    } else {
      _controller!.value = 0;
    }
  }

  //自定义Widget
  renderDropDownCustomWidget() {
    _currentMenuIndex = widget.controller.menuIndex;

    _isShowDropDownItemWidget = !_isShowDropDownItemWidget;
    // if (widget.dropdownMenuChanging != null) {
    //   widget.dropdownMenuChanging!(
    //       _isShowDropDownItemWidget, _currentMenuIndex);
    // }
    if (!_isShowMask) {
      _isShowMask = true;
    }

    _dropDownHeight = 308;
    if (widget.menuWidgetHeight != null) {
      _dropDownHeight = widget.menuWidgetHeight!(_currentMenuIndex);
    }
    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    _animation = Tween(begin: 0.0, end: _dropDownHeight).animate(_controller!)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);

    if (_isControllerDisposed) return;

    if (widget.controller.isShow) {
      _controller!.forward();
    } else if (widget.controller.isShowHideAnimation) {
      _controller!.reverse();
    } else {
      _controller!.value = 0;
    }
  }

  void _animationStatusListener(AnimationStatus status) {
    switch (status) {
      case AnimationStatus.dismissed:
        _isShowMask = false;
        // if (widget.dropdownMenuChanged != null) {
        //   widget.dropdownMenuChanged!(false, _currentMenuIndex);
        // }
        break;
      case AnimationStatus.forward:
        break;
      case AnimationStatus.reverse:
        break;
      case AnimationStatus.completed:
        // if (widget.dropdownMenuChanged != null) {
        //   widget.dropdownMenuChanged!(true, _currentMenuIndex);
        // }
        break;
    }
  }

  void _animationListener() {
    // var heightScale = _animation!.value / _dropDownHeight!;
    // _maskColorOpacity = widget.maskColor.opacity * heightScale;
//    print('$_maskColorOpacity');
    //这行如果不写，没有动画效果
    setState(() {});
  }

  Widget _mask() {
    if (_isShowMask) {
      double menuTop = widget.controller.dropDownMenuTop ?? 0;
      double menuHeight = _animation == null ? 0 : _animation!.value;
      //如果下拉是固定位置的，那么底部蒙版的高度必须剪去菜单的高度，非固定则不减
      double maskHeight = MediaQuery.of(context).size.height -
          menuTop -
          (widget.isFixure ? menuHeight : 0);
      return GestureDetector(
        onTap: () {
          if (widget.isUseOverlay) {
            widget.controller.resetPullDownState();
          } else {
            widget.controller.hide();
          }
        },
        child: Container(
          margin: EdgeInsets.only(top: widget.isFixure ? 0 : menuTop),
          width: double.infinity,
          height: maskHeight,
          color: widget.maskColor,
        ),
      );
    } else {
      return Container(
        height: 0,
      );
    }
  }

  Widget _buildDropDownWidget() {
    int menuIndex = widget.controller.menuIndex;

    var topMaskHeight = 0.0;
    double dropDownMenuTop = widget.controller.dropDownMenuTop ?? 0;
    if (!widget.isFixure) {
      MediaQueryData mediaQuery = MediaQuery.of(context);
      topMaskHeight = mediaQuery.size.height - dropDownMenuTop;
    }
    if (_isCustomWidget()) {
      //自定义
      return Positioned(
          top: widget.controller.dropDownMenuTop,
          left: 0,
          right: 0,
          child: Column(
            children: <Widget>[
              widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller) !=
                      null
                  ? Container(
                      color: Colors.white,
                      width: double.infinity,
                      height: _animation == null ? 0 : _animation!.value,
                      child: widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller),
                    )
                  : Container(),
              widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller) !=
                      null
                  ? _mask()
                  : Container(),
            ],
          ));
    } else {
      List<dynamic>? list = getMenuData();

      if (_animation == null) {
        setState(() {});
      }

      return widget.isFixure
          ? Positioned(
              top: dropDownMenuTop,
              left: 0,
              right: 0,
              child: Column(
                children: <Widget>[
                  renderSearchBar(menuIndex),
                  renderLine(menuIndex),
                  Container(
                    color: Colors.white,
                    width: double.infinity,
                    height: _animation == null ? 0 : _animation!.value,
                    child: renderbuildConditionListWidget(list),
                  ),
                  _mask(),
                ],
              ))
          : Stack(
              clipBehavior: Clip.none,
              children: [
                Positioned(
                  top: 0,
                  right: 0,
                  left: 0,
                  bottom: topMaskHeight,
                  child: GestureDetector(
                    onTap: () {
                      if (widget.isUseOverlay) {
                        widget.controller.resetPullDownState();
                      } else {
                        widget.controller.hide();
                      }
                    },
                    child: Container(
                      color: Colors.transparent,
                      width: double.infinity,
                    ),
                  ),
                ),
                _mask(),
                Container(
                  margin: EdgeInsets.only(top: dropDownMenuTop),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      renderSearchBar(menuIndex),
                      renderLine(menuIndex),
                      Container(
                        color: Colors.white,
                        width: double.infinity,
                        height: _animation == null ? 0 : _animation!.value,
                        child: renderbuildConditionListWidget(list),
                      ),
                    ],
                  ),
                ),
              ],
            );
    }
  }

  //搜索框
  Widget renderSearchBar(int menuIndex) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      if (list != null && list.length > 8 && _isShowMask) {
        if (_aliveSearchContent != null) {
          List? result = widget.searchResultCallback!(
              menuIndex, _aliveSearchContent ?? '');
          if (result != null) {
            _aliveSearch[menuIndex] = result;
            renderDropDownWidget();
            setState(() {});
          }
        }
        return KqSearchBar(
          onCancel: () {
            _aliveSearch.remove(_currentMenuIndex);
            _aliveSearchContent = null;
            if (widget.menuDataRender != null) {
              widget.menuDataRender!(menuIndex);
            }
            renderDropDownWidget();
            setState(() {});
          },
          onSubmit: (p0, state0) {
            if (p0 == '') {
              // _aliveSearch[menuIndex] = [];
              _aliveSearch.remove(_currentMenuIndex);
              _aliveSearchContent = null;
              renderDropDownWidget();
              // if (widget.cancelSearchCallback != null) {
              //   widget.cancelSearchCallback!(menuIndex);
              // }
              // setState(() {});
            } else {
              if (widget.searchResultCallback != null) {
                List? result = widget.searchResultCallback!(menuIndex, p0);
                if (result != null && result.isNotEmpty) {
                  // widget.menuData![menuIndex] = result;
                  _aliveSearch[menuIndex] = result;
                  _aliveSearchContent = p0;
                } else {
                  _aliveSearch[menuIndex] = [];
                  _aliveSearchContent = null;
                }
                renderDropDownWidget();
                setState(() {});
              }
            }
          },
        );
      }
    }
    return const SizedBox();
  }

  Widget renderLine(int menuIndex) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      if (list != null && list.length > 8 && _isShowMask) {
        return const KqDivider();
      }
    }
    return const SizedBox();
  }

  renderbuildConditionListWidget(items) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      List<dynamic>? searchList = _aliveSearch[_currentMenuIndex];
      if (searchList != null) {
        //说明正在搜索
        list = searchList;
      }
      if (list != null && list.isNotEmpty && _isShowMask) {
        return ListView.separated(
          shrinkWrap: true,
          padding: EdgeInsets.zero,
          scrollDirection: Axis.vertical,
          // item 的个数
          itemCount: items.length,
          // 添加分割线
          separatorBuilder: (BuildContext context, int index) =>
              const Divider(height: 1.0),
          itemBuilder: (BuildContext context, int index) {
            return gestureDetector(items, index);
          },
        );
      }
    }
    //显示暂无数据
    return Container(
      color: Colors.white,
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(12, 10, 0, 0),
      height: _animation == null ? 0 : _animation!.value,
      child: Text(
        KqIntl.currentResource.noDataTip,
        textAlign: TextAlign.start,
        style: TextStyle(
            fontSize: KqThemeManager.getFormConfig().headerFontSize,
            color: KqThemeColors.text59),
      ),
    );
  }

  GestureDetector gestureDetector(items, int index) {
    var currentItem = items[index];
    var selectItem = widget.controller.chosenData[widget.controller.menuIndex];
    String titleStr = widget.menuItemRender!(currentItem);
    bool isSelcted = widget.isDataSame!(currentItem, selectItem);
    bool isShowSort = false;
    if (widget.isShowSortRender != null) {
      isShowSort = widget.isShowSortRender!(widget.controller.menuIndex);
    }
    return GestureDetector(
      onTap: () {
        widget.controller.isRemoveMenu = true;
        widget.controller.changeChosenData(currentItem);
        widget.controller.hide();
        if (widget.pullDownCallback != null) {
          //回调
          widget.pullDownCallback!(currentItem, widget.controller.menuIndex);
        }
      },
      child: SizedBox(
        width: double.infinity,
        height: 44,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 16,
            ),
            isShowSort
                ? Container(
                    margin: EdgeInsets.fromLTRB(0, 0, 16, 0),
                    decoration: BoxDecoration(
                      color: KqThemeColors.bgF0,
                      borderRadius: BorderRadius.circular(11),
                    ),
                    child: Container(
                      alignment: AlignmentDirectional.center,
                      width: 22,
                      height: 22,
                      child: Text(
                        index.toString(),
                        style: TextStyle(
                            color: KqThemeColors.text26,
                            fontSize:
                                KqThemeManager.getFormConfig().headerFontSize),
                      ),
                    ),
                  )
                : const SizedBox(),
            Expanded(
              child: Text(
                titleStr,
                style: TextStyle(
                  fontSize: KqThemeManager.getFormConfig().headerFontSize,
                  color: isSelcted
                      ? const Color(0xFF3A559B)
                      : KqThemeColors.text26,
                ),
              ),
            ),
            isSelcted
                ? Icon(
                    Icons.check,
                    color: const Color(0xFF3A559B),
                    size: 16,
                  )
                : const SizedBox(),
            SizedBox(
              width: 16,
            ),
          ],
        ),
      ),
    );
  }
}
